package com.murong.ai.coder.domain.database;

import com.murong.ai.coder.domain.GenerateCodeService;
import com.murong.ai.coder.entity.TableEntity;
import com.murong.ai.coder.enums.StatusEnum;
import com.murong.ai.coder.infrastructure.converter.DatabaseConvert;
import com.murong.ai.coder.infrastructure.repository.dao.TableDataDao;
import com.murong.ai.coder.infrastructure.repository.dao.TableRecordDao;
import com.murong.ai.coder.infrastructure.repository.po.TableDataPO;
import com.murong.ai.coder.infrastructure.repository.po.TableRecordPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AfterSqlExecuteService {

    @Autowired
    TableDataDao tableDataDao;
    @Autowired
    TableRecordDao tableRecordDao;
    @Autowired
    GenerateCodeService codeServ;

    public void updateError(TableRecordPO record) {
        //更新执行失败
        TableRecordPO indexPO = new TableRecordPO();
        indexPO.setId(record.getId());
        record.setStatus(StatusEnum.FAIL.getKey());
        tableRecordDao.updateByOne(record,indexPO);
    }

    public void handleRecord(TableRecordPO record) {
        //更新执行成功
        TableRecordPO indexPO = new TableRecordPO();
        indexPO.setId(record.getId());
        record.setStatus(StatusEnum.SUCCESS.getKey());
        tableRecordDao.updateByOne(record,indexPO);

        //存储数据
        TableDataPO po = DatabaseConvert.toPO(record);
        TableDataPO dataIndex = new TableDataPO();
        dataIndex.setTableNameCamel(po.getTableNameCamel());
        TableDataPO resultPO = tableDataDao.queryOne(dataIndex);
        if(resultPO != null) {
            tableDataDao.updateByOne(po,dataIndex);
        }else {
            tableDataDao.insert(po);
        }

        //更新最终记录
        record.setStatus(StatusEnum.STORED.getKey());
        tableRecordDao.updateByOne(record,indexPO);

        //生成相关代码
        TableEntity entity = DatabaseConvert.toEntity(po);
        codeServ.generTableCode(entity);
    }
}
